//
//  CDHomeViewController.m
//  CollectToDesktop
//
//  Created by 王启颖 on 2020/10/15.
//  Copyright © 2020 godbe. All rights reserved.
//

#import "CDHomeViewController.h"
#import "CDHomeHeadView.h"
#import "LXHSlideView.h"
#import "ContentView.h"
#import "YNPageViewController.h"
#import "CDLogoViewController.h"
#import "UIViewController+SideMenu.h"
#import "thirdViewController.h"
#import "CDSoftwareViewController.h"
#import "CDSelectLogoViewController.h"
#import "CDGuideViewController.h"
#import "CDGuide2ViewController.h"
#import "AppDelegate.h"
#import <ZLPhotoActionSheet.h>
#import <Photos/Photos.h>
#import "CDNoNetworkView.h"
@interface CDHomeViewController ()<YNPageViewControllerDataSource, YNPageViewControllerDelegate>
@property (nonatomic, strong) CDHomeHeadView *homeHeadView;
@property (nonatomic, strong) LXHSlideView *slideView;
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong) UIImage *logoImage;
@property (nonatomic, strong) NSDictionary *appDic;
@property (nonatomic, strong) NSString *encodedImageStr;
@property (nonatomic, strong) NSMutableArray *wallpaperArr;
@property (nonatomic, strong) CDNoNetworkView *noNetworkView;
@end

@implementation CDHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    
    // 改背景图
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav"] forBarMetrics:(UIBarMetricsDefault)];

   // 去掉阴影
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"更多"] forState:UIControlStateNormal];
    [button setFrame:CGRectMake(0, 0, 60, 40)];
    button.contentEdgeInsets = UIEdgeInsetsMake(0, -20,0, 0);
    [button addTarget:self action:@selector(navigationItemBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem =  item;
    
    
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.titleLabel.font = [UIFont systemFontOfSize:14];
    [button2 setImage:[UIImage imageNamed:@"问号"] forState:UIControlStateNormal];
    [button2 setTitle:@"如何使用" forState:UIControlStateNormal];
    [button2 setTitleColor:[UIColor jg_colorHex:0x00C35D] forState:UIControlStateNormal];
    [button2 setFrame:CGRectMake(0, 0, 60, 40)];
    button2.contentEdgeInsets = UIEdgeInsetsMake(0, 20,0, 0);
    [button2 addTarget:self action:@selector(navigationItemRight) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithCustomView:button2];
    self.navigationItem.rightBarButtonItem =  item2;

    
    
    
    thirdViewController * vc = [[thirdViewController alloc]init];
    vc.hideSideClickBlock = ^{
        [self hideSideMenuView:YES comletion:nil];
    };
    [self setSideMenuController:vc sideMenuDirection:SideMenuDirection_left attribute:@{k_Menu_width_key:@(200),k_mask_color_key:[[UIColor blackColor] colorWithAlphaComponent:0.2]}];
    
    
    
    [self request];
    
}

-(void)navigationItemBack{
    [self showSideMenuView:YES];
}

-(void)navigationItemRight{
    CDGuide2ViewController *vc = [[CDGuide2ViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setupPageVC {
    
    YNPageConfigration *configration = [YNPageConfigration defaultConfig];
    configration.pageStyle = YNPageStyleSuspensionCenter;
    configration.headerViewCouldScale = YES;
    /// 控制tabbar 和 nav
    configration.showTabbar = NO;
    configration.showNavigation = YES;
    configration.scrollMenu = YES;
    configration.aligmentModeCenter = NO;
    configration.lineWidthEqualFontWidth = YES;
    configration.showBottomLine = YES;
    configration.lineColor = [UIColor clearColor];
    configration.selectedItemColor = [UIColor whiteColor];
    /// 设置悬浮停顿偏移量
    configration.bottomLineBgColor = [UIColor clearColor];
    configration.itemMargin = 15;
    configration.scrollViewBackgroundColor = [UIColor whiteColor];
    configration.converColor = [UIColor jg_colorHex:0x00C35E];
    configration.showConver = YES;
    
    YNPageViewController *vc = [YNPageViewController pageViewControllerWithControllers:self.getArrayVCs
                                                                                titles:[self getArrayTitles]
                                                                                config:configration];
    vc.dataSource = self;
    vc.delegate = self;
  
    vc.headerView = [self headView];

    /// 作为自控制器加入到当前控制器
    [vc addSelfToParentViewController:self];
    
    /// 如果隐藏了导航条可以 适当改y值
    //    pageVC.view.yn_y = kYNPAGE_NAVHEIGHT;
    
//    [self.view addSubview:self.navView];
}

- (NSArray *)getArrayVCs {
    NSMutableArray *arr = [[NSMutableArray alloc]init];

    for (int i = 0; i<self.wallpaperArr.count; i++) {
        NSDictionary *dic = self.wallpaperArr[i];
        CDLogoViewController *vc2 = [[CDLogoViewController alloc] init];
        vc2.bgID = dic[@"id"];
        [arr addObject:vc2];
    }

    return arr;
}

- (NSArray *)getArrayTitles {
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    
    for (int i = 0; i<self.wallpaperArr.count; i++) {
        NSDictionary *dic = self.wallpaperArr[i];
        [arr addObject:dic[@"wallpaperClassificationName"]];
    }

    return arr;
}



#pragma mark - YNPageViewControllerDataSource
- (UIScrollView *)pageViewController:(YNPageViewController *)pageViewController pageForIndex:(NSInteger)index {
    CDLogoViewController *vc = pageViewController.controllersM[index];

    return [(CDLogoViewController *)vc tableView];

}

#pragma mark - YNPageViewControllerDelegate
- (void)pageViewController:(YNPageViewController *)pageViewController
            contentOffsetY:(CGFloat)contentOffset
                  progress:(CGFloat)progress {
//    NSLog(@"--- contentOffset = %f, progress = %f", contentOffset, progress);
//    self.navView.backgroundColor = UIColor.blackColor;
}














-(CDHomeHeadView *)homeHeadView{
    if (!_homeHeadView) {
        _homeHeadView = [CDHomeHeadView szd_initUIView];
        _homeHeadView.frame = CGRectMake(0, 0, kDeviceWidth, 345);
        WEAKSELF
        _homeHeadView.selectLogoClickBlock = ^{
            UIAlertController *vc = [[UIAlertController alloc]init];
            // 2.创建并添加按钮
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"OK Action");
                [weakSelf showWithPreview];
            }];
            UIAlertAction *logoAction = [UIAlertAction actionWithTitle:@"素材库" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"OK Action");
                CDSelectLogoViewController *vc = [[CDSelectLogoViewController alloc]init];
                
                vc.logoClickBlock = ^(UIImage * _Nonnull img) {
                    weakSelf.logoImage = img;
                };
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }];
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"Cancel Action");
            }];

            [vc addAction:okAction];           // A
            [vc addAction:logoAction];           // A
            [vc addAction:cancelAction];       // B
            [weakSelf presentViewController:vc animated:YES completion:nil];
        };
        _homeHeadView.selectSoftwareClickBlock = ^{
            CDSoftwareViewController *vc = [[CDSoftwareViewController alloc]init];
            vc.softClickBlock = ^(NSDictionary * _Nonnull dic) {
                [weakSelf.homeHeadView.appBtn sd_setImageWithURL:[NSURL URLWithString:dic[@"artworkUrl60"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"photoAndVideoDefault"]];
                weakSelf.appDic = dic;
                weakSelf.homeHeadView.appTextfield.placeholder = dic[@"trackName"];
                weakSelf.homeHeadView.createBtn.backgroundColor = [UIColor jg_colorHex:0x00C35D];
                [weakSelf.homeHeadView.createBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            };
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        _homeHeadView.createLogoClickBlock = ^{
            if (!weakSelf.appDic) {
                [SVProgressHUD showImage:NULL_IMAGE status:@"请选择app～～"];
            }else{
                [weakSelf provision];
            }
        };
        return _homeHeadView;
    }
    return _homeHeadView;
}

-(LXHSlideView *)slideView{
    if (!_slideView) {
        
        NSString *file = [[NSBundle mainBundle] pathForResource:@"Slide" ofType:@"plist"];
        NSMutableDictionary*dataDic = [[NSMutableDictionary alloc]initWithContentsOfFile:file];
        NSLog(@"%@",dataDic);
        NSArray *arr = [NSMutableArray arrayWithArray:dataDic[@"slide"]];
        NSMutableArray *viewControllers = [[NSMutableArray alloc]init];
        for (int i = 0; i<arr.count; i++) {
            NSDictionary *d = arr[i];
            ContentView *contentView = [[ContentView alloc]init];
            WEAKSELF
            contentView.logoClickBlock = ^(NSDictionary * _Nonnull dic) {
                weakSelf.logoImage = [UIImage imageNamed:dic[@"logoPic"]];
            };
            contentView.dataArr = d[@"slideIcon"];
            NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:contentView,d[@"slideTile"], nil];
            [viewControllers addObject:dic];
        }

        _slideView = [[LXHSlideView alloc]initWithFrame:CGRectMake(0, _homeHeadView.bottom + 56, kDeviceWidth, 150) WithViewControllers:viewControllers];
    }
    return _slideView;
}

- (void)setLogoImage:(UIImage *)logoImage{
    _logoImage = logoImage;
    [self.homeHeadView.logoBtn setImage:logoImage forState:UIControlStateNormal];
    
    self.encodedImageStr = [self UIImageToBase64Str:logoImage];
}

- (NSString *)UIImageToBase64Str:(UIImage *)image

{
    NSData *data = UIImagePNGRepresentation(image);

    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    return encodedImageStr;

}

// 根据url获取图片
- (UIImage *)getImageFromURL:(NSString *)fileURL
{
    UIImage *result;
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    result = [UIImage imageWithData:data];
    return result;
}

-(UIView *)headView{
    if (!_headView) {
        _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kDeviceWidth, 610)];
        _headView.backgroundColor = [UIColor jg_colorHex:0xF0F0F0];
        [self.view addSubview:_headView];
        
        [_headView addSubview:self.homeHeadView];
        
        UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(10, _homeHeadView.bottom, kDeviceWidth, 56)];
        titleLab.text = @"更多图标";
        [_headView addSubview:titleLab];
        
        [_headView addSubview:self.slideView];
        
        UILabel *titleLab2 = [[UILabel alloc]initWithFrame:CGRectMake(10, _slideView.bottom, kDeviceWidth, 56)];
        titleLab2.text = @"壁纸系列";
        [_headView addSubview:titleLab2];
    }
    return _headView;
}

- (void)provision {
    //模板位置
    NSString *templatePath = [[NSBundle mainBundle] pathForResource:@"phone_template" ofType:@"mobileconfig"];
    
    //目标位置
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"profile.mobileconfig"];
    
    
    NSString *str=[NSString stringWithContentsOfFile:templatePath encoding:NSUTF8StringEncoding error:nil];
    
    if (self.encodedImageStr.length == 0) {
        self.encodedImageStr = [self UIImageToBase64Str:[self getImageFromURL:_appDic[@"artworkUrl60"]]];
    }
    
    
    str = [NSString stringWithFormat:str,self.encodedImageStr,self.homeHeadView.appTextfield.text,self.homeHeadView.appTextfield.text,_appDic[@"bundleId"],_appDic[@"bundleId"],self.homeHeadView.appTextfield.text,_appDic[@"bundleId"]];
    NSLog(@"%@",str);
    
    
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    }
    
    NSError *error;
    [str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
    
//    BOOL success = [[NSFileManager defaultManager] copyItemAtPath:templatePath toPath:path error:nil];

    __weak AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    UInt16 port = appDelegate.httpServer.port;
    NSLog(@"%u", port);
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:%u/profile.mobileconfig", port]] options:[NSDictionary new] completionHandler:nil];

}


-(CDNoNetworkView *)noNetworkView{
    if (!_noNetworkView) {
        _noNetworkView = [CDNoNetworkView szd_initUIView];
        _noNetworkView.frame = self.view.bounds;
        [self.view addSubview:_noNetworkView];
    }
    return _noNetworkView;
}


- (void)showWithPreview
{
    ZLPhotoActionSheet *a = [self getPas];

    [a showPreviewAnimated:YES];

}


#pragma mark - 懒加载 -
//选择照片
- (ZLPhotoActionSheet *)getPas {
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    actionSheet.configuration.allowForceTouch = NO;
    
    //是否可以选择视频
    actionSheet.configuration.allowSelectVideo = NO;
    actionSheet.configuration.allowTakePhotoInLibrary = YES;
    //设置照片最大预览数
    actionSheet.configuration.maxPreviewCount = 20;
    actionSheet.configuration.editAfterSelectThumbnailImage = YES;
    actionSheet.configuration.maxSelectCount = 1;
    actionSheet.configuration.allowEditImage = YES;
    //是否在已选择照片上显示遮罩层
    actionSheet.configuration.showSelectedMask = YES;
    actionSheet.configuration.clipRatios =@[GetClipRatio(1, 1)];
    //actionSheet.configuration.showEditTypeClip = YES;
    
    actionSheet.sender = self;
    
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        
        if (images.count > 0) {
            self.logoImage = images[0];
        }
        
    }];
    
    return actionSheet;
}


#pragma mark - 网络请求
-(void)request{

    NSString *urlstr=[NSString stringWithFormat:@"https://gapi.szlzyd.com/0010/na/icon/wallpaperClassifcation"];
    [[CDNetworkRequset HttpRequstManager] PostURL:urlstr params:[[NSMutableDictionary alloc]init] success:^(NSInteger code, id  _Nonnull result) {

        self.wallpaperArr = [NSMutableArray arrayWithArray:result[@"data"]];
        [self setupPageVC];
    } fail:^(NSError * _Nonnull error) {
        [self noNetworkView];
        [self.noNetworkView setHidden:NO];
        [self.view bringSubviewToFront:self.noNetworkView];
        WEAKSELF
        self.noNetworkView.reloadClickBlock = ^{
            [weakSelf request];
        };
    }];
}


@end
